#include<iostream>
#include<pthread.h>
#include<unistd.h>


#define NUM 5

class tickets
{
  private:
    pthread_mutex_t mymutex; 
    int ticket;
    
  public:
    tickets():ticket(1000)
  {
    pthread_mutex_init(&mymutex,nullptr);  //初始化锁
  }
  
    ~tickets()
    {
      pthread_mutex_destroy(&mymutex); //销毁锁
    }

    bool GetTicket()
    {
      int falg = true;
      pthread_mutex_lock(&mymutex);
      //抢票
      if(ticket > 0)
      {
          usleep(1000);
          std::cout<<pthread_self()<<"抢了第"<<ticket<<"张票"<<std::endl;   
          ticket--;
          printf("");
      }
      else 
      {
        printf("票已售空\n");
        falg = false;
    
      }
     
      pthread_mutex_unlock(&mymutex);
      return falg;
    }
};


//线程执行
void* pthread_run(void * avg)
{
    tickets *t =(tickets*)avg;
    while(true)
    {
      if(!t->GetTicket())
      {
        break;
      }
    }
    return nullptr;
}



int main()
{
    tickets *t  = new tickets();
    //创建线程
    pthread_t tids[NUM]; 
    for(int i = 0 ; i < NUM ; i++)
    {
      int* id = new int(i);
      pthread_create(tids+(*id),nullptr,pthread_run,(void*)t);  
    }

    //主等待线程
    for(int i = 0 ; i < NUM ; i++)
    {
      pthread_join(tids[i],nullptr);
    }

    return 0;
}
